package com.atwulidin.config;

import com.atwulidin.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

// 该项目还没有用accessToken来访问资源
// 当前项目为认证授权中心
@Component
@EnableAuthorizationServer
public class AuthorizationConfig extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        // 允许表单提交，检查accessToken是否有效
        security.allowFormAuthenticationForClients()
                .checkTokenAccess("permitAll()");
    }

    /**
     * 分配我们的appid和appkey(或clentid和clientkey)
     *
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        // 实际工作中读数据库获得appid和appsecret
        clients.inMemory()
                // appid
                .withClient("mayikt_appid")
                // appsecret
                .secret(passwordEncoder.encode("mayikt_pwd"))
                // 授权码
                .authorizedGrantTypes("authorization_code","refresh_token")
                // 作用域：表示所有的接口都可以访问，分配我们的appid调用接口的权限
                .scopes("all")
                .resourceIds("mayikt_resource")
                // 用户选择授权之后，跳转到该地址传递code授权码
                .redirectUris("http://www.mayikt.com/callback");
    }

    // 刷新accessToken时用到
    @Autowired
    private UserService userService;
    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                // 自定义登录逻辑
                .userDetailsService(userService)
                // 授权管理器
                .authenticationManager(authenticationManager);
    }

}